/*
 * Copyright (C) 2006 the xine-project
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * $Id: console_output.c,v 1.1 2006/03/27 22:48:57 dsalt Exp $
 *
 * Permissive console output transliteration
 */

#include "config.h"
#include "console_output.h"

#include <stdio.h>
#include <glib.h>

static GIConv xlate;

static void
xlate_write (const char *text, FILE *stream)
{
  gsize read = 0, written = 0;
  while (*text)
  {
    GError *error = NULL;
    text += read;
    char *buf = g_convert_with_iconv (text, -1, xlate, &read, &written, &error);
    if (buf && *buf)
      fputs (buf, stream);
    else if (error)
    {
      g_error_free (error);
      error = NULL;
      buf = g_convert_with_iconv (text, read, xlate, &read, &written, &error);
      if (buf && *buf)
	fputs (buf, stream);
      else
      {
	if (error)
	  g_error_free (error);
	fputc ('?', stream);
	if (!read && *text)
	  read = 1;
      }
    }
    g_free (buf);
    if (!read)
      break;
  }
}

static void
xlate_g_print (const char *text)
{
  xlate_write (text, stdout);
}

static void
xlate_g_printerr (const char *text)
{
  xlate_write (text, stderr);
}

void
console_output_init (void)
{
  const char *cset;
  g_get_charset (&cset);
  char *dest = g_strconcat (cset, "//TRANSLIT", NULL);
  xlate = g_iconv_open (dest, "utf-8");
  g_free (dest);
  g_set_print_handler (xlate_g_print);
  g_set_printerr_handler (xlate_g_printerr);
}
